/**
 * @Description: 客户管理相关API
 * @Author: lujq
 * @Date: 2025-01-04
 * @LastEditors: lujq
 * @LastEditTime: 2025-01-04 10:54:00
 */

import { http } from './index'
import type { Customer, PageResponse, PageParams, CustomerAnalytics } from '@/types'

/**
 * 获取客户列表
 * @param params 查询参数
 * @returns 客户列表
 */
export const getCustomerList = async (
  params: PageParams & {
    keyword?: string
    status?: string
    level?: string
    province?: string
    customerType?: string
  },
) => {
  console.log('API调用开始，参数:', params)
  
  try {
    // 构建查询URL，包含分页和过滤参数
    const queryParams = new URLSearchParams()
    queryParams.append('page', params.page.toString())
    queryParams.append('pageSize', params.pageSize.toString())
    
    if (params.keyword) queryParams.append('keyword', params.keyword)
    if (params.status) queryParams.append('status', params.status)
    if (params.level) queryParams.append('level', params.level)
    if (params.province) queryParams.append('province', params.province)
    if (params.customerType) queryParams.append('customerType', params.customerType)
    
    const response = await http.get<{
      items: Customer[]
      total: number
      page: number
      pageSize: number
      totalPages: number
    }>(`/customers?${queryParams.toString()}`)
    
    console.log('API响应成功:', response)
    
    // 转换为前端期望的格式
    return {
      ...response,
      data: {
        list: response.data.items,
        total: response.data.total,
        page: response.data.page,
        pageSize: response.data.pageSize
      }
    }
  } catch (error) {
    console.error('API调用失败:', error)
    throw error
  }
}

/**
 * 获取客户详情
 * @param id 客户ID
 * @returns 客户详情
 */
export const getCustomerDetail = (id: string) => {
  return http.get<Customer>(`/customers/${id}`)
}

/**
 * 创建客户
 * @param data 客户数据
 * @returns 创建结果
 */
export const createCustomer = (data: Omit<Customer, 'id' | 'createTime' | 'updateTime'>) => {
  return http.post<Customer>('/customers', {
    ...data,
    id: Date.now().toString(),
    createTime: new Date().toISOString(),
    updateTime: new Date().toISOString(),
  })
}

/**
 * 更新客户
 * @param id 客户ID
 * @param data 客户数据
 * @returns 更新结果
 */
export const updateCustomer = (id: string, data: Partial<Customer>) => {
  return http.put<Customer>(`/customers/${id}`, {
    ...data,
    updateTime: new Date().toISOString(),
  })
}

/**
 * 删除客户
 * @param id 客户ID
 * @returns 删除结果
 */
export const deleteCustomer = (id: string) => {
  return http.delete(`/customers/${id}`)
}

/**
 * 批量删除客户
 * @param ids 客户ID列表
 * @returns 删除结果
 */
export const batchDeleteCustomers = (ids: string[]) => {
  return Promise.all(ids.map((id) => deleteCustomer(id)))
}

/**
 * 获取客户分析数据
 * @returns 客户分析数据
 */
export const getCustomerAnalytics = () => {
  return http.get<CustomerAnalytics>('/analytics/customers')
}

/**
 * 获取客户地区分布
 * @returns 地区分布数据
 */
export const getCustomerRegionDistribution = () => {
  return http.get('/analytics/customer-regions')
}

/**
 * 导出客户数据
 * @param params 查询参数
 * @returns 客户数据
 */
export const exportCustomers = async (params: any) => {
  // 获取所有客户数据用于导出
  const response = await http.get<Customer[]>('/customers')
  return response
}
